import _ from 'underscore';
import Mn from 'backbone.marionette';
import {
    formatDate
} from 'date.js';
import {
    formatAmount,
} from 'math.js';
import Radio from 'backbone.radio';

const template = require('./templates/TaskLineView.mustache');

const TaskLineView = Mn.View.extend({
    tagName: 'tr',
    className: 'row taskline',
    template: template,
    ui: {
        up_button: 'button.up',
        down_button: 'button.down',
        edit_button: 'button.edit',
        delete_button: 'button.delete'
    },
    triggers: {
        'click @ui.up_button': 'order:up',
        'click @ui.down_button': 'order:down',
        'click @ui.edit_button': 'edit',
        'click @ui.delete_button': 'delete'
    },
    modelEvents: {
        'change': 'render'
    },
    initialize(options) {
        this.config = Radio.channel('config');
        this.tva_options = this.config.request('get:options', 'tvas');
        this.product_options = this.config.request('get:options', 'products');
        this.user_prefs = Radio.channel('user_preferences');
        this.section = options['section'];
        this.useDate = this.section.hasOwnProperty('date');
    },
    getTvaLabel() {
        let res = "";
        let current_value = this.model.get('tva');
        _.each(this.tva_options, function (tva) {
            if (tva.value == current_value) {
                res = tva.name;
            }
        });
        return res
    },
    getProductLabel() {
        let res = "";
        let current_value = this.model.get('product_id');
        _.each(this.product_options, function (product) {
            if (product.id == current_value) {
                res = product.label;
            }
        });
        return res
    },
    templateContext() {

        let min_order = this.model.collection.getMinOrder();
        let max_order = this.model.collection.getMaxOrder();
        let order = this.model.get('order');
        let full_cost = formatAmount(this.model.get('cost'), false);
        let cost = this.user_prefs.request('formatAmount', this.model.get('cost'), false);
        let is_rounded = cost != full_cost;
        let date = this.model.get('date');

        return {
            ht: this.user_prefs.request('formatAmount', this.model.ht(), false),
            ttc: this.user_prefs.request('formatAmount', this.model.ttc(), false),
            date: date ? formatDate(date) : 'non précisée',
            hasDate: this.useDate,
            product: this.getProductLabel(),
            tva_label: this.getTvaLabel(),
            is_not_first: order != min_order,
            is_not_last: order != max_order,
            cost_amount: cost,
            full_cost_amount: full_cost,
            is_rounded: is_rounded,
            edit: this.getOption('edit'),
            is_ttc_mode: this.getOption('is_ttc_mode'),
            can_delete: this.section['can_delete']
        };

    }
});
export default TaskLineView;